import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
})
export class LoginComponent implements OnInit {
  validateForm!: FormGroup;
  uuid = this.getUUID();
  captchaUrl = `sola/captcha?uuid=${this.uuid}`;

  constructor(private fb: FormBuilder, private http: HttpClient,
              private router: Router) {}

  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    console.log(this.validateForm);
    // 校验通过后登陆
    if (this.validateForm.valid) {
      this.validateForm.value.uuid = this.uuid;
      // 登陆
      this.login();
    }
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      username: [null, [Validators.required]],
      password: [null, [Validators.required]],
      captcha: [null, [Validators.required]],
      remember: [true],
    });
  }

  refreshCaptcha() {
    console.log(this.captchaUrl);
    this.uuid = this.getUUID();
    this.captchaUrl = `sola/captcha?uuid=${this.uuid}`;
  }

  login() {
    this.http.post('login', this.validateForm.value)
      .subscribe((res: any) => {
        if (res.code === 200){
          localStorage.setItem('token', res.data.token);
          // 获取用户信息
          this.http.get('sys/user/info').subscribe(console.log);
          this.router.navigateByUrl('home');
        }else{
          this.refreshCaptcha();
        }
      });
  }

  getUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
      const r = (Math.random() * 16) | 0,
        v = c === 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
  }
}
